﻿/* Copyright (c) 2010 EPiServer AB
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
 * to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
 * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Text;
using System.Web;
using System.Web.Hosting;
using System.Web.UI;
using EPiServer.Core;
using EPiServer.SpecializedProperties;
using EPiServer.Web.Hosting;

namespace EPiServer.Municipality.Web.UI.WebControls {
    /// <summary>
    /// Summary description for LinkTemplateContainer.
    /// </summary>
    /// <remarks>
    /// </remarks>
    public class LinkTemplateContainer : Control, INamingContainer {
        private const string NewWindowCssClass = "popup";

        /* *******************************************************************
        *  Properties 
        * *******************************************************************/
        #region public LinkItem CurrentLinkItem
        /// <summary>
        /// Get/Sets the CurrentLinkItem of the LinkTemplateContainer
        /// </summary>
        /// <value></value>
        public LinkItem CurrentLinkItem { get; set; }
        #endregion
        #region public string Link
        /// <summary>
        /// Gets the Link of the LinkTemplateContainer
        /// </summary>
        /// <value></value>
        public string Link {
            get {
                string mappedHref = CurrentLinkItem.GetMappedHref();
                PageReference pageRef = PageReference.ParseUrl(mappedHref);
                if (!PageReference.IsNullOrEmpty(pageRef)) {
                    PageData page = DataFactory.Instance.GetPage(pageRef);
                    return CreateLink(page.LinkURL, HttpUtility.HtmlEncode(page.PageName), false);
                } 
                if (IsFile) {
                    if (mappedHref.IndexOf("?") > 0)
                        mappedHref = mappedHref.Substring(0, mappedHref.LastIndexOf("?"));
                    if (FileSize.Equals(string.Empty))
                        return CreateLink(mappedHref, HttpUtility.HtmlEncode(CurrentLinkItem.Text), true);
                    return CreateLink(mappedHref, HttpUtility.HtmlEncode(CurrentLinkItem.Text) + " (" + FileSize + ")", true);
                }

                return CreateLink(mappedHref, HttpUtility.HtmlEncode(CurrentLinkItem.Text), false);
            }
        }
        #endregion
        #region public string FileSize
        /// <summary>
        /// Gets the FileSize of the LinkTemplateContainer
        /// </summary>
        /// <value></value>
        public string FileSize {
            get {
                if (_fileSize != null)
                    return _fileSize;

                UnifiedFile uFile = null;
                try {
                    uFile = HostingEnvironment.VirtualPathProvider.GetFile(CurrentLinkItem.Href) as UnifiedFile;
                } catch {
                    _fileSize = string.Empty;
                }
                if (uFile != null) {
                    if (uFile.Length < 1024)
                        _fileSize = uFile.Length + "&nbsp;bytes";
                    else if ((uFile.Length >= 1024) && (uFile.Length < 1024000))
                        _fileSize = Convert.ToInt16(uFile.Length / 1024) + "&nbsp;kB";
                    else
                        _fileSize = Math.Round(((1.0 * uFile.Length) / 1024000), 2) + "&nbsp;MB";
                }
                return _fileSize;
            }
        }
        private string _fileSize;
        #endregion
        #region public bool IsFile
        /// <summary>
        /// Gets the IsFile of the LinkTemplateContainer
        /// </summary>
        /// <value></value>
        /// <returns>True if it is file, otherwise false.</returns>
        public bool IsFile {
            get {
                try {
                    return HostingEnvironment.VirtualPathProvider.FileExists(CurrentLinkItem.Href);
                } catch {
                    return false;
                }
            }
        }
        #endregion
        #region public string Extension
        /// <summary>
        /// Gets the Extension of the LinkTemplateContainer
        /// </summary>
        /// <value></value>
        public string Extension {
            get {
                if (_extension == null) {
                    string fileExtension = CurrentLinkItem.Href.Substring(CurrentLinkItem.Href.LastIndexOf(".") + 1);

                    //Fix for document links in dynamic content, they are saved with "?epslanguage" querystring
                    if (fileExtension.IndexOf("?") > 0)
                        fileExtension = fileExtension.Substring(0, fileExtension.LastIndexOf("?"));

                    _extension = fileExtension.ToLower();
                }
                return _extension;
            }
        }
        private string _extension;
        #endregion
        
        /* *******************************************************************
         *  Constructors 
         * *******************************************************************/
        #region public LinkTemplateContainer(LinkItem linkItem)
        /// <summary>
        /// Initializes a new instance of the <b>LinkTemplateContainer</b> class.
        /// </summary>
        /// <param name="linkItem"></param>
        public LinkTemplateContainer(LinkItem linkItem) {
            CurrentLinkItem = linkItem;
        }
        #endregion

        /* *******************************************************************
         *  Methods 
         * *******************************************************************/
        #region private string CreateLink(string href, string text, bool forceNewWindow)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="href"></param>
        /// <param name="text"></param>
        /// <param name="forceNewWindow"></param>
        /// <returns></returns>
        private string CreateLink(string href, string text, bool forceNewWindow) {

            StringBuilder builder = new StringBuilder();
            builder.Append("<a");
            foreach (string key in CurrentLinkItem.Attributes.Keys) {
                string str;
                if (string.IsNullOrEmpty(CurrentLinkItem.Attributes[key])) {
                    continue;
                }

                if (key.Equals("target")) {
                    if (CurrentLinkItem.Attributes[key].Equals("_blank"))
                        builder.Append(string.Format(" {0}=\"{1}\"", "class", NewWindowCssClass));
                    continue;
                }
                if (forceNewWindow) {
                    builder.Append(string.Format(" {0}=\"{1}\"", "class", NewWindowCssClass));
                }
                if (key.Equals("href")) {
                    str = href;
                } else {
                    str = CurrentLinkItem.Attributes[key];
                }
                builder.Append(string.Format(" {0}=\"{1}\"", key, str));
            }
            builder.Append(string.Format(">{0}</a>", text));
            return builder.ToString();
        }
        #endregion
    }
}